package com.wanchuang.hepos.ui.page.main;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.architecture.utils.Utils;
import com.wanchuang.hepos.BuildConfig;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.app.App;
import com.wanchuang.hepos.bridge.data.bean.ServiceBean;
import com.wanchuang.hepos.bridge.data.bean.UserBean;
import com.wanchuang.hepos.bridge.data.repository.Apis;
import com.wanchuang.hepos.bridge.request.MineRequestViewModel;
import com.wanchuang.hepos.bridge.state.main.MineFragmentViewModel;
import com.wanchuang.hepos.databinding.FragmentMineBinding;
import com.wanchuang.hepos.help.ImageHelper;
import com.wanchuang.hepos.help.PermissionHelper;
import com.wanchuang.hepos.help.UserHelper;
import com.wanchuang.hepos.bridge.data.repository.WebApis;
import com.wanchuang.hepos.net.NetworkManager;
import com.wanchuang.hepos.net.interfaces.OnRequestCallBack;
import com.wanchuang.hepos.proto.MemberOuterClass;
import com.wanchuang.hepos.ui.base.BaseFragment;
import com.wanchuang.hepos.ui.page.login.MENetworkFourFragment;
import com.wanchuang.hepos.ui.web.ui.WebViewActivity;

import static cn.jiguang.dy.Protocol.mContext;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class MineFragment extends BaseFragment {


    private FragmentMineBinding mBinding;
    private MineFragmentViewModel mViewModel;
    private MineRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MineFragmentViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(MineRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        mBinding = FragmentMineBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRequestViewModel.getErrorString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });
        mRequestViewModel.getResultString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });
        mRequestViewModel.getMember().observe(this, member -> {
            UserBean userBean = new UserBean(member);
            UserHelper.syncCurrentUserInfo(userBean);
            mViewModel.info.set(userBean);
            switch (member.getMerchantLevel()) {
                case "1":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_level_putong);
                    break;
                case "2":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_level_huangjin);
                    break;
                case "3":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_leve_baijin);
                    break;
                case "4":
                    mBinding.ivLevel.setBackgroundResource(R.mipmap.icon_level_zhuanshi);
                    break;
            }
            if (member.getMerchantType().equals("1")) {
                mBinding.ivShopType.setBackgroundResource(R.mipmap.icon_wei);
            } else {
                mBinding.ivShopType.setBackgroundResource(R.mipmap.icon_biao);

            }
        });
        mRequestViewModel.getKfuBean().observe(this, get_kfu_info -> {
            ServiceBean serviceBean = new ServiceBean();
            serviceBean.setMember_id(get_kfu_info.getMemberId());
            serviceBean.setMember_name(get_kfu_info.getMemberName());
            serviceBean.setMember_mobile(get_kfu_info.getMemberMobile());
            serviceBean.setMember_avatar(get_kfu_info.getMemberAvatar());
            serviceBean.setChat_id(get_kfu_info.getChatId());
            serviceBean.setChat_pwd(get_kfu_info.getChatPwd());
            UserHelper.saveKeFuUserInfo(serviceBean);
        });
        mRequestViewModel.getMemberInfo();
        mRequestViewModel.get_kfu_info();


        NetworkManager.INSTANCE.post(Apis.sys_switch, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.sys_switch systeLog = MemberOuterClass.sys_switch.parseFrom(bytes);
                mViewModel.coupon_switch.set(systeLog.getCouponSwitch().equals("1"));
            }

            @Override
            public void onError(int code, String errorMessage) {
            }
        });


    }

    public class ClickProxy {
        public void GoToNext(View view) {
            switch (view.getId()) {
                case R.id.rv_info:
                    nav().navigate(R.id.action_mainRootFragment_to_mineInfoFragment);
                    break;
                case R.id.rv_message:
                    nav().navigate(R.id.action_mainRootFragment_to_messageFragment);
                    break;
                case R.id.rv_question:
                    WebViewActivity.startActivity(mActivity, WebApis.commonProblem);
                    break;
                case R.id.rv_up:
                    WebViewActivity.startActivity(mActivity, WebApis.merchantsLevel);
                    break;
                case R.id.rv_feedback:
                    nav().navigate(R.id.action_mainRootFragment_to_feedBackFragment);
                    break;
                case R.id.rv_coupon:
                    nav().navigate(R.id.action_mainRootFragment_to_couponFragment);
                    break;
                case R.id.rv_setting_change:
                    nav().navigate(R.id.action_mainRootFragment_to_changeSettingFragment);
                    break;

            }
        }

        public void setting() {
            nav().navigate(R.id.action_mainRootFragment_to_mineSettingFragment);
        }

        /**
         * 拨打电话（跳转到拨号界面，用户手动点击拨打）
         */
        public void takePhone() {
            PermissionHelper.getInstance().getPermission(mActivity, new PermissionHelper.PermissionCallBack() {
                @Override
                public void onSuccess() {
                    startChat();
                }
                @Override
                public void onFail() {
                    showShortToast("请先允许权限再使用此功能");
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


        }

        private void startChat() {
            boolean login = ChatHelper.getInstance().isLogin();
            if (login) {
                // 打开客服聊天
                ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                ChatActivity.startActivity(mActivity, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
            } else {
                showShortToast("聊天登录中");
                Log.e("MineChatId", "startChat: "+ UserHelper.getUser().getChat_id());
                App.getChatHelper().login(UserHelper.getUser().getChat_id(), UserHelper.getUser().getChat_pwd(), new LoginCallBack() {
                    @Override
                    public void onSuccess() {
                        //判断是否为客服
                        // 打开客服聊天
                        ServiceBean keFuInfo = UserHelper.getKeFuInfo();
                        mActivity.runOnUiThread(() -> showShortToast("人工客服回复时间：工作日9:00-12:00；13:30-18:00"));
                        ChatActivity.startActivity(mActivity, keFuInfo.getMember_id() + "", keFuInfo.getMember_name(), keFuInfo.getMember_avatar(), keFuInfo.getChat_id(), keFuInfo.getMember_mobile());
                    }

                    @Override
                    public void onError(int code, String message) {
                        mActivity.runOnUiThread(() -> showShortToast("聊天暂时登录失败"));
                    }
                });
            }
        }
    }
}
